//
//  LRXBringingController.m
//  路人侠
//
//  Created by zhangxulong on 3/14/16.
//  Copyright © 2016 zhangxulong. All rights reserved.
//

#import "LRXBringingController.h"
#import "LRXBringingHearView.h"
#import "LRXBringingCell.h"
#import "LRXHelpMeInfoModel.h"
#import "AppDelegate.h"
#import "LRXDistributionController.h"
#import "UIButton+WebCache.h"
#import "LRXAccpetOrderView.h"

@interface LRXBringingController()<
    UITableViewDataSource,
    UITableViewDelegate,
    sliderDeleteCell,
    LRXAppDelegate,
    LRXBringHearViewDeleate
>
@property (nonatomic,strong) LRXBringingHearView * headView;
@property (nonatomic,strong) NSIndexPath * selectIndexPath;
@property (nonatomic,strong) NSMutableArray * helpMesgs;
@property (nonatomic,strong) NSMutableArray * cellMaxHeight;
@property (nonatomic,strong) NSMutableArray * cellHeight;
@property (nonatomic,strong) NSMutableArray * cellTableStates;
@property (nonatomic,strong) NSMutableArray * selectItems;
@property (nonatomic,weak ) UITableView * tableView;
@property (nonatomic,strong) UIView * selectItemView;
@property (nonatomic,strong) UIView * selecUserIcon;
@property (nonatomic,weak) UIView * lineView;
@property (nonatomic,assign) NSInteger selectItemCount;
@property (nonatomic,weak) AppDelegate * appDelegate;
@property (nonatomic,weak) LRXAccpetOrderView * orderView;
@property (nonatomic,weak) UIView * mengban;
@end
@implementation LRXBringingController
- (LRXBringingHearView *)headView
{
    if (_headView == nil) {
        _headView = [[LRXBringingHearView alloc]init];
    }
    return _headView;
}
- (NSMutableArray *)selectItems
{
    if (_selectItems == nil) {
        _selectItems = [NSMutableArray array];
    }
    return _selectItems;
}
- (UIView *)selecUserIcon
{
    if (_selecUserIcon == nil) {
        _selecUserIcon = [[UIView alloc]init];
    }
    return _selecUserIcon;
}

- (NSMutableArray *)helpMesgs{
    if (_helpMesgs == nil) {
        _helpMesgs = [NSMutableArray array];
    }
    return _helpMesgs;
}
- (NSMutableArray *)cellHeight{
    if (_cellHeight == nil) {
        _cellHeight = [NSMutableArray array];
    }
    return _cellHeight;
}
- (NSMutableArray *)cellMaxHeight
{
    if (_cellMaxHeight == nil) {
        _cellMaxHeight = [NSMutableArray array];
    }
    return _cellMaxHeight;
}
- (NSMutableArray *)cellTableStates
{
    if (_cellTableStates == nil) {
        _cellTableStates = [NSMutableArray array];
    }
    return _cellTableStates;
}
- (NSIndexPath *)selectIndexPath
{
    if (_selectIndexPath == nil) {
        _selectIndexPath = [[NSIndexPath alloc]initWithIndexes:0 length:0];
    }
    return _selectIndexPath;
}

- (void)viewDidLoad{
    
    self.navigationItem.title = @"正在帮带";
    //?????
    self.navigationItem.backBarButtonItem = nil;
    
    self.view.backgroundColor = mainColor;
    self.selectItemCount = 0;
    
    self.appDelegate =  (AppDelegate *)[[UIApplication sharedApplication] delegate];
    self.appDelegate.appDelegate = self;
    if (self.appDelegate.userRole == USERNORMALTYPE) {
        
        [MBProgressHUD showError:@"您没有发送帮带信息" toView:self.view];
        [self popBringView];
    }
    else if(self.appDelegate.userRole == USERHELPERTYPR)
    {
        [self loadData];
        
        //更新已经接单的数据
        [self layoutAccpItem];
        
        //更新视图数据
        [self.tableView reloadData];
    }
    self.view.backgroundColor = [UIColor whiteColor];
}
- (void)loadData
{
    [MBProgressHUD showMessage:nil toView:self.view];
    AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
    [manger POST:getHandledWaiterUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
            
        
        NSInteger status_code = [responseObject[@"data"][@"status_code"] integerValue];
        if (status_code == 1) {
            [self handleDate:responseObject];
            //更新已经接单的数据
            [self layoutAccpItem];
            //更新视图数据
            [self.tableView reloadData];
        }
        else if(status_code == 2){
            [MBProgressHUD showError:@"请重新登陆"];
            [self popBringView];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

//头部视图的设置
- (void)setHeadSubViews:(NSArray *)info{
    self.headView.frame = CGRectMake(0, 0, self.view.frame.size.width, 510 * hScale);
    if (info.count > 0) {
        self.headView.stTimeText = info[0];
        self.headView.endTimeText = info[1];
        self.headView.stAddrText = info[2];
        self.headView.endAddrText = info[3];
    }

    
    [self.headView layoutBringingView];
    self.headView.LRXBringingHeadDelegate = self;
    
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headView.frame) - 95 * hScale, self.view.frame.size.width, 3 * hScale)]; lineView.backgroundColor = [UIColor colorWithRed:229 green:229 blue:229];
    UIView * lineView2 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headView.frame) , self.view.frame.size.width, 3 * hScale)]; lineView2.backgroundColor = [UIColor colorWithRed:229 green:229 blue:229];
    self.lineView = lineView;
    [self.headView addSubview:lineView2];
    [self.headView addSubview:lineView];
    
}
//设置内容视图
- (void)setTableView
{
    UITableView * contentView = [[UITableView alloc]init];
    CGFloat contentViewMaxH = self.view.frame.size.height;
    contentView.frame = CGRectMake(0, 0, self.view.frame.size.width,contentViewMaxH);
    contentView.delegate = self;
    contentView.dataSource = self;
    contentView.rowHeight = 177 * hScale;
    contentView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    contentView.backgroundColor = mainColor;

    
    contentView.showsVerticalScrollIndicator = NO;
    
    
    //这里有错误 不应该是 200
    for (int i = 0 ; i < 200; i++) {
        [self.cellHeight addObject:@(contentView.rowHeight)];
        [self.cellTableStates addObject:@(YES)];
    }
    
    
    
    
    contentView.tableHeaderView = self.headView;
    self.tableView = contentView;
    [self.view addSubview:contentView];
}

//--------------------------------------------------------------------------------------------------------------------appleDatgate 的代理方法
- (void)updateNewPushThing:(LRXHelpMeInfoModel *)pushThing
{
   
    //更新数据
    [self.helpMesgs insertObject:pushThing atIndex:0];
    //更新视图数据
    [self.tableView reloadData];
    
    
    
}

//--------------------------------------------------------------------------------------------------------------------tableView的代理方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    static NSString * BRINGINGCELLREUSED = @"BRINGINGCELLREUSED";
    LRXBringingCell * cell = [tableView dequeueReusableCellWithIdentifier:BRINGINGCELLREUSED];
    if (cell == nil) {
        cell = [[LRXBringingCell alloc]init];
    }
    
    [cell layoutSubviews:self.helpMesgs[indexPath.row]];

    cell.tableView.hidden = [self.cellTableStates[indexPath.row] boolValue];
    cell.jiedan.hidden = [self.cellTableStates[indexPath.row] boolValue];
    
    cell.deleteCellDelegate = self;
    
//    NSString * cellHeight = [NSString stringWithFormat:@"%.2lf",cell.cellHeight];
    //最大的cell高度
    [self.cellMaxHeight addObject: @(cell.cellHeight)];

    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSNumber * number = self.cellHeight[indexPath.row];
    return [number floatValue];
}

//点击cell的调用
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath];
    CGPoint tableViewOffect;
    static CGPoint tableViewOffectPoint;
    
    //展开
    if (cellRect.size.height <= (170 + 10)* hScale ) {
        self.cellHeight[indexPath.row] = self.cellMaxHeight[indexPath.row];
        self.cellTableStates[indexPath.row] = @(NO);
        
        CGFloat cellMaxY = cellRect.origin.y + [self.cellHeight[indexPath.row] floatValue] + CGRectGetMaxY(self.headView.frame);
        CGFloat viewMaxH = MainScreenH - statuesH - NavbarH;
        CGFloat h =  cellMaxY > viewMaxH ? cellMaxY - viewMaxH : 0;
        tableViewOffect = CGPointMake(0, h);
        tableViewOffectPoint = self.tableView.contentOffset;
        
    }
    else //收缩
    {
        self.cellHeight[indexPath.row] = @(177 * hScale);
        self.cellTableStates[indexPath.row] = @(YES);
        tableViewOffect = tableViewOffectPoint;
    }
  
    //动态提高界面的高度
    [UIView animateWithDuration:0.3 animations:^{
        self.tableView.contentOffset = tableViewOffect;
    }];
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
   
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.helpMesgs.count;
}


//－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－------------－－------------－－－－－－－－－－－－－－－－cell的代理方法 点击接单
- (void)accpetBtnClick:(LRXBringingCell *)selectCell
{
    //只能接6个
    if (self.selectItems.count <= 6) {
        [MBProgressHUD showMessage:@"正在接单"];
        
        AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
        NSDictionary * param = @{@"w_q_id":selectCell.model.itemID};
        [manger POST:acceptRequestUrl parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
            int statusCode = [responseObject[@"data"][@"status_code"] intValue];
            if (statusCode == 1) {
                [MBProgressHUD showSuccess:@"接单成功"];
            
                CGFloat sep = 88 * wScale;
                UIButton * selectUserIconBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                selectUserIconBtn.frame = selectCell.userView.frame;
                selectUserIconBtn.layer.cornerRadius = selectCell.userView.frame.size.width * 0.5;
                selectUserIconBtn.layer.masksToBounds = YES;
                [selectUserIconBtn setImage:selectCell.userView.image forState:UIControlStateNormal];
                [selectUserIconBtn addTarget:self action:@selector(accpetOrderClick:) forControlEvents:UIControlEventTouchUpInside];
                selectUserIconBtn.center = [selectCell.userView convertPoint:selectCell.userView.center toView:self.tableView];
                selectUserIconBtn.tag = self.selectItems.count;
                [self.tableView addSubview:selectUserIconBtn];
                [self.selectItems addObject:selectCell.model];
                //点击接单 动画
                CAKeyframeAnimation * keyAnimation = [CAKeyframeAnimation animation];
                keyAnimation.keyPath = @"position";
                NSValue * values1 = [NSValue valueWithCGPoint:selectUserIconBtn.center];
                NSValue * values2 = [NSValue valueWithCGPoint:CGPointMake(94 * wScale + (self.selectItemCount * sep), self.lineView.frame.origin.y + 50 * hScale)];
                keyAnimation.values = @[values1,values2];
                keyAnimation.duration = 0.5;
                keyAnimation.removedOnCompletion=NO;
                keyAnimation.fillMode=kCAFillModeForwards;
                selectUserIconBtn.center = CGPointMake(94 * wScale + (self.selectItemCount++ * sep), self.lineView.frame.origin.y + 50 * hScale);
                [selectUserIconBtn.layer addAnimation:keyAnimation forKey:nil];
                
                
                //删除接单的item
                NSIndexPath *indexPath = [self.tableView indexPathForCell:selectCell];
                [self.helpMesgs removeObjectAtIndex:indexPath.row];
                [self.cellTableStates removeObjectAtIndex:indexPath.row];
                [self.cellMaxHeight removeObjectAtIndex:indexPath.row];
                [self.cellHeight removeObjectAtIndex:indexPath.row];
                [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
                
                
            }
            if (statusCode == 2) {
                [MBProgressHUD showError:@"请重新登录"];
            }
            if (statusCode == 3) {
                [MBProgressHUD showError:@"订单已被抢了"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self slideToDeleteCell:selectCell];
                });
                
            }
            if (statusCode == 4) {
                [MBProgressHUD showError:@"请求不符合接受条件"];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSLog(@"%@",error);
        }];
        [MBProgressHUD hideHUD];
    }
    else  //如果接满后 就不能接单了
    {
        
    }
}

-(void)slideToDeleteCell:(LRXBringingCell *)slideDeleteCell{

    AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
    NSDictionary * param = @{@"w_q_id":slideDeleteCell.model.itemID};
    [manger POST:uninterestedUrl parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSIndexPath *indexPath = [self.tableView indexPathForCell:slideDeleteCell];
        [self.helpMesgs removeObjectAtIndex:indexPath.row];
        [self.cellTableStates removeObjectAtIndex:indexPath.row];
        [self.cellMaxHeight removeObjectAtIndex:indexPath.row];
        [self.cellHeight removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}

//----------------------------------------------------------------------------------------------------------------开始配送 head的代理方法
- (void)pushDistributionController
{
    if (self.selectItems.count <= 0) {
        [MBProgressHUD showError:@"您未接订单"];
    }
    else
    {
        AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
        [MBProgressHUD showMessage:nil];
        [manger POST:startDeliveryUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [MBProgressHUD hideHUD];
            LRXDistributionController * controller = [[LRXDistributionController alloc]init];
            controller.selectItemArray = self.selectItems;
            
            //改变身份状态
            self.appDelegate.userRole = @"1b";
            
            [self.navigationController pushViewController:controller animated:YES];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD hideHUD];
            NSLog(@"%@",error);
        }];
        
        
    }

    
    
}
//----------------------------------------------------------------------------------------------------------------

- (void)accpetOrderClick:(UIButton *)accpetOrderBtn
{
    UIView * backgroundView = [[UIView alloc]init];
    backgroundView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.54];
    backgroundView.frame = CGRectMake(0, 0, 640 * wScale, MainScreenH);
    self.mengban = backgroundView;
    //手势 点击
    UITapGestureRecognizer * pin1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(mengbanClick)];
    [backgroundView addGestureRecognizer:pin1];
    
    
    LRXAccpetOrderView * orderView = [LRXAccpetOrderView accpetOrderWithModel:self.selectItems[accpetOrderBtn.tag]];
    
    orderView.frame = CGRectMake(48 * wScale, 140 * hScale, 545 * wScale, 663 * hScale);
    self.orderView = orderView;
    
    CAKeyframeAnimation * bringAni = [CAKeyframeAnimation animation];
    bringAni.keyPath = @"transform.scale";
    bringAni.values = @[@0,@1];
    bringAni.duration = 0.15;
    [orderView.layer addAnimation:bringAni forKey:nil];
    
    [self.view addSubview:backgroundView];
    [self.view addSubview:orderView];

    
    
}
- (void)mengbanClick
{
    [self.mengban removeFromSuperview];
    [self.orderView removeFromSuperview];
}
- (void)popBringView
{
    [self.navigationController popViewControllerAnimated:YES];
}

//处理数据历史数据
- (void)handleDate:(NSDictionary *)responseObject
{
    NSMutableArray * headInfo = [NSMutableArray array];
    //帮带信息
    if (![responseObject[@"data"][@"dataset"][@"helper_info"] isEqual:[NSNull null]]) {
        
        NSString * backStartTime = responseObject[@"data"][@"dataset"][@"helper_info"][@"back_start_time"];
        NSString * backEndTime = responseObject[@"data"][@"dataset"][@"helper_info"][@"back_end_time"];
        NSString * startAddrText = responseObject[@"data"][@"dataset"][@"helper_info"][@"location"][@"back_position"];
        NSString * endAddrText = responseObject[@"data"][@"dataset"][@"helper_info"][@"location"][@"to_position"];
        [headInfo addObject:backStartTime];
        [headInfo addObject:backEndTime];
        [headInfo addObject:startAddrText];
        [headInfo addObject:endAddrText];
        
        
    }
    [self setHeadSubViews:headInfo];
    
   

    
    //已接单的数据
    for (NSDictionary * modelDic in responseObject[@"data"][@"dataset"][@"accepted_waiters"]) {
        
        LRXHelpMeInfoModel * model = [LRXHelpMeInfoModel helpModelWithDic:modelDic];
        [self.selectItems addObject:model];
        
    }
 
    //已经推送但是，还没有接受的订单
    for (NSDictionary * modelDic in responseObject[@"data"][@"dataset"][@"matched_waiters"]) {

        LRXHelpMeInfoModel * model = [LRXHelpMeInfoModel helpModelWithDic:modelDic];
    
        [self.helpMesgs addObject:model];
    }

    
    NSInteger statusCode = [responseObject[@"data"][@"status_code"] integerValue];
    if ( statusCode == 2) {
        [MBProgressHUD showError:@"请登录"];
    }
    
    //设置内容视图
    [self setTableView];
}

//布局 已接受的的订单
-(void)layoutAccpItem
{
    CGFloat sep = 88 * wScale;
    for (int i = 0; i < self.selectItems.count; i++) {
        LRXHelpMeInfoModel * selectModel = self.selectItems[i];
        NSString * userIconStr = routeImageUrl;
        if (selectModel.userIcon && selectModel.userIcon.length > 0) {
            userIconStr =  [userIconStr stringByAppendingString:selectModel.userIcon];
        }
        
        userIconStr = [userIconStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        NSURL * url = [NSURL URLWithString:userIconStr];
        UIButton * seletImageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        seletImageBtn.tag = i;
        [seletImageBtn sd_setImageWithURL:url forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"de"]];
        seletImageBtn.center = CGPointMake(94 * wScale + (self.selectItemCount++ * sep), self.lineView.frame.origin.y + 50 * hScale);
        seletImageBtn.bounds = CGRectMake(0, 0, 60 * wScale, 60 * wScale);
        seletImageBtn.layer.cornerRadius = 30 * wScale;
        seletImageBtn.layer.masksToBounds = YES;
        [seletImageBtn addTarget:self action:@selector(accpetOrderClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.tableView addSubview:seletImageBtn];
    }
}
@end
